package LeetCode.Interview;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class offer03 {
    public int findRepeatNumber1(int[] nums) {
        Set<Integer> set = new HashSet<>();
        for (int num : nums) {
            if (set.contains(num)){
                return num;
            }
            set.add(num);
        }
        return -1;
    }

    // 暴力On方
    public int findRepeatNumber2(int[] nums) {
        if (nums.length < 2){
            return -1;
        }
        for (int i = 0; i < nums.length; i++){
            for (int j = i + 1; j < nums.length; j++){
                if (nums[i] == nums[j]){
                    return nums[i];
                }
            }
        }
        return -1;
    }

    // 排序之后进行比较
    public int findRepeatNumber3(int[] nums) {
        if (nums.length < 2){
            return -1;
        }
        Arrays.sort(nums);
        for (int i = 1; i < nums.length; i++){
            if (nums[i] == nums[i - 1]){
                return nums[i];
            }
        }
        return -1;
    }

    // 原地置换算法
    public int findRepeatNumber4(int[] nums){
        int temp = 0;
        for (int i = 0; i < nums.length; i++){
            while (nums[i] != i){
                if (nums[i] == nums[nums[i]]){
                    return nums[i];
                }
                temp = nums[i];
                nums[i] = nums[temp];
                nums[temp] = temp;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        int[] nums = {2, 3, 1, 0, 2, 5, 3};
        System.out.println(new offer03().findRepeatNumber4(nums));
    }
}
